package com.tanhua.dubbo.server.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.UserLogApi;
import com.tanhua.dubbo.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: UserTokenInterceptor
 * @Author:王晨晗
 * @Description: token令牌拦截器
 * @Date: 2021/12/30/11:09
 */
@Component
public class UserTokenInterceptor implements HandlerInterceptor {
    //心跳机制,存放token及用户操作;
    private static Map countMap = new ConcurrentHashMap<String,Object>();
    @Reference
    private UserLogApi userLogApi;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验handler是否是handlerMethod
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //判断是否包含指定注解(即不需要校验的请求进行放行)
        if (((HandlerMethod)handler).hasMethodAnnotation(NoAuthorization.class)){
            return true;
        }

        //从请求头中获取token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)){
            User user = userService.queryToken(token);
            if (user != null){
                //token有效存入ThreadLocal中
                UserThreadLocal.set(user);
                //记录用户的心跳
                //判断map中是否存在token
                if (ObjectUtil.isNotEmpty(countMap.get(token))){
                    Object oldTime = countMap.get(token);   //获取到原有时间;
                    //拿当前时间减去上次请求时间;
                    long time = Convert.toLong(oldTime).longValue();
                    long nowTime = System.currentTimeMillis();
                    long countTime = nowTime - time;
                    //将时间保存到map中;
                    countMap.put(token , nowTime);
                    //判断时间是否在5分钟 , 在五分钟内计入操作时长
                    if (countTime/1000 < 5 * 60){
                        userLogApi.updateOrInsert(user.getId() , countTime);
                    }
                    return true;
                }
                //记录token进入map
                countMap.put(token , System.currentTimeMillis());
                //执行新增日志操作
                userLogApi.updateOrInsert(user.getId() , 0L);
                //放行;
                return true;
            }
        }

        //token无效,响应401
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
